package com.hjtech.base.retroft;

import android.util.Log;

import com.google.gson.GsonBuilder;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/*
 * 项目名:    Pigeon
 * 包名       cn.hjtech.directory.common
 * 文件名:    BaseApi
 * 创建者:    ZJB
 * 创建时间:  2017/5/3 on 14:08
 * 描述:     TODO
 */
public class BaseApi {

    protected Retrofit init(String baseUrl) {
        return new Retrofit.Builder()
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
                        .setLenient()
                        .create()
                ))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//支持RxJava
                .client(getOkHttpClient())
                .baseUrl(baseUrl)
                .build();

    }

    protected Retrofit init(String baseUrl, PrintLogInterface printLogInterface) {
        this.printLogInterface = printLogInterface;
        return new Retrofit.Builder()
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
                        .setLenient()
                        .create()
                ))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//支持RxJava
                .client(getOkHttpClient())
                .baseUrl(baseUrl)
                .build();

    }

    /**
     * 自定义OkHttpClient拦截请求参数并加上 加密参数
     */
    private OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //日志显示级别
        HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.HEADERS;
        //新建log拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
//                Log.d("ApiUrl", "--->" + message);
                if (printLogInterface != null) {
                    printLogInterface.printLog(message);
                } else {
                    Log.d("ApiUrl", "--->" + message);
                }
            }
        });
        loggingInterceptor.setLevel(level);
        builder.addInterceptor(loggingInterceptor);

        //设置超时
//        builder.connectTimeout(15, TimeUnit.SECONDS);
//        builder.readTimeout(15, TimeUnit.SECONDS);
//        builder.writeTimeout(15, TimeUnit.SECONDS);
        //错误重连
        builder.retryOnConnectionFailure(true);
        return builder.build();
    }

    PrintLogInterface printLogInterface;


    protected interface PrintLogInterface {
        void printLog(String msg);
    }
}
